/**
 * $Revision$
 * $Date$
 *
 * Copyright (C) https://gitee.com/baibaiclouds/platform . All rights reserved.
 * <p>
 * This software is the confidential and proprietary information of .
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with .
 * 
 * Modified history:
 *   baibai  2021年4月24日 下午6:06:00  created
 */
package com.desktop.web.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.desktop.web.config.ErrorCode;
import com.desktop.web.service.remotecpe.NatInfo;
import com.desktop.web.service.websession.WebSession;
import com.desktop.web.service.websession.WebSessionService;

/**
 * 
 *
 * @author baibai
 */
public class WebAuthHandlerInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(WebAuthHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            WebSession webSession = WebSessionService.webSessionService.refreshToken(request.getParameter("token"));
            if (webSession != null) {
                request.setAttribute("webSession", webSession);
                return true;
            }

            NatInfo natInfo = WebSessionService.webSessionService.refreshUUID(request.getParameter("uuid"));
            if (natInfo != null) {
                webSession = new WebSession(natInfo.getUid(), natInfo.getUsername(), natInfo.getUuid());
                webSession.setLastTime(natInfo.getLastDate());
                request.setAttribute("webSession", webSession);
                return true;
            }

            Map<String, Object> result = new HashMap<String, Object>();
            result.put("code", ErrorCode.RESET_LOGIN);
            result.put("message", "invalid token");
            result.put("success", false);
            response.getWriter().write(JSON.toJSONString(result).toString());
            return false;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

}
